import { Injectable, NotFoundException } from '@nestjs/common';
import { CreateBannerDto } from './dto/create-banner.dto';
import { UpdateBannerDto } from './dto/update-banner.dto';
import { Banner } from './entities/banner.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';

@Injectable()
export class BannerService {
  constructor(
    @InjectRepository(Banner)
    private bannerRepository: Repository<Banner>,
  ) {}

  /**
   * 创建新的轮播图
   * @param createBannerDto 轮播图数据
   * @returns 创建的轮播图
   */
  async create(createBannerDto: CreateBannerDto): Promise<Banner> {
    const banner = this.bannerRepository.create({
      ...createBannerDto,
      // 确保默认值
      isActive: createBannerDto.isActive ?? true,
      order: createBannerDto.order ?? 0,
    });
    
    return await this.bannerRepository.save(banner);
  }

  /**
   * 获取所有轮播图
   * @returns 轮播图列表
   */
  async findAll(): Promise<Banner[]> {
    return await this.bannerRepository.find({
      order: {
        order: 'ASC',
        createdAt: 'DESC',
      },
    });
  }

  /**
   * 获取激活状态的轮播图
   * @returns 激活状态的轮播图列表
   */
  async findActive(): Promise<Banner[]> {
    return await this.bannerRepository.find({
      where: { isActive: true },
      order: { order: 'ASC' },
    });
  }

  /**
   * 根据ID获取单个轮播图
   * @param id 轮播图ID
   * @returns 轮播图对象
   */
  async findOne(id: number): Promise<Banner> {
    const banner = await this.bannerRepository.findOneBy({ id });
    if (!banner) {
      throw new NotFoundException(`轮播图不存在，ID: ${id}`);
    }
    return banner;
  }

  /**
   * 更新轮播图
   * @param id 轮播图ID
   * @param updateBannerDto 更新数据
   * @returns 更新后的轮播图
   */
  async update(id: number, updateBannerDto: UpdateBannerDto): Promise<Banner> {
    const banner = await this.findOne(id);
    const updatedBanner = this.bannerRepository.merge(banner, updateBannerDto);
    return await this.bannerRepository.save(updatedBanner);
  }

  /**
   * 删除轮播图
   * @param id 轮播图ID
   */
  async remove(id: number): Promise<{
    success: boolean;
    message: string;
  }> {
    const banner = await this.bannerRepository.findOneBy({ id });
    if (!banner) {
      throw new NotFoundException(`轮播图不存在，ID: ${id}`);
    }

    await this.bannerRepository.delete(id);
    
    return {
      success: true,
      message: '轮播图删除成功',
    };
  }

  /**
   * 更新轮播图的激活状态
   * @param id 轮播图ID
   * @param isActive 是否激活
   * @returns 更新后的轮播图
   */
  async updateStatus(id: number, isActive: boolean): Promise<Banner> {
    const banner = await this.findOne(id);
    banner.isActive = isActive;
    return await this.bannerRepository.save(banner);
  }

  /**
   * 批量更新轮播图排序
   * @param banners 包含id和order的轮播图数组
   */
  async updateOrder(banners: { id: number; order: number }[]): Promise<void> {
    for (const item of banners) {
      await this.bannerRepository.update(item.id, { order: item.order });
    }
  }
}
